package com.own.dondeestoy;

import java.io.InputStream;
import java.net.URL;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.own.dondeestoy.core.Card;

public class CardAdapter extends ArrayAdapter<Card> {

	Context context;
	int layoutResourceId;
	Card objects[] = null;
	float imageWidth;

	public CardAdapter(Context context, int layoutResourceId, Card[] objects) {
		super(context, layoutResourceId, objects);
		this.context = context;
		this.layoutResourceId = layoutResourceId;
		this.objects = objects;
	}

	public CardAdapter(Context context, int layoutResourceId, List<Card> objects) {
		super(context, layoutResourceId, objects);
		this.context = context;
		this.layoutResourceId = layoutResourceId;
		this.objects = objects.toArray(new Card[objects.size()]);
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		final ComponentsHolder holder;
		final int cc = position;

		// row = null; // This clears the view, so the rows are well drawn but
		// makes the app much slower

		if (row == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			row = inflater.inflate(layoutResourceId, parent, false);

			holder = new ComponentsHolder();
			holder.id = (TextView) row.findViewById(R.id.lblId);
			holder.lat = (TextView) row.findViewById(R.id.lblLat);
			holder.lng = (TextView) row.findViewById(R.id.lblLng);
			holder.address = (TextView) row.findViewById(R.id.lblAddress);
			holder.name = (TextView) row.findViewById(R.id.lblName);
			holder.descr = (TextView) row.findViewById(R.id.lblDescr);
			holder.photo = (ImageView) row.findViewById(R.id.imgPhoto);
			holder.navigate = (Button) row.findViewById(R.id.btnNavigate);
			holder.moreInfo = (Button) row.findViewById(R.id.btnMoreInfo);
			holder.buttonsBackground = (LinearLayout) row
					.findViewById(R.id.llBtnBackgrounds);

			row.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// ver si corresponde agregar codigo
				}
			});

			row.setTag(holder);
		} else {
			holder = (ComponentsHolder) row.getTag();
			holder.id.setText("");
			holder.lat.setText("");
			holder.lng.setText("");
			holder.address.setText("");
			holder.name.setText("");
			holder.descr.setText("");
			holder.photo.setVisibility(View.GONE);
			holder.buttonsBackground.setBackgroundColor(MainActivity.context
					.getResources().getColor(R.color.Black));
			holder.buttonsBackground.setTag("");

		}

		Card componentsList = objects[cc];

		holder.id.setText((String.valueOf(componentsList.getId())));
		holder.lat.setText((String.valueOf(componentsList.getLat())));
		holder.lng.setText((String.valueOf(componentsList.getLng())));
		holder.address.setText(componentsList.getAddress());
		holder.name.setText(componentsList.getName());
		holder.descr.setText(componentsList.getDescription());

		// if (holder.buttonsBackground.getTag() != null &&
		// holder.buttonsBackground.getTag().equals("")) {
//		Random rdn = new Random();
		// holder.buttonsBackground.setTag("S");
//		if (holder.buttonsBackground.getTag() == null)
//			holder.buttonsBackground.setTag("");

//		switch ((holder.buttonsBackground.getTag().equals("")) ? rdn.nextInt(6)
//				: Integer.valueOf(holder.buttonsBackground.getTag().toString())) {
		switch (componentsList.getCardtypeid()) {
		case 1:
			holder.buttonsBackground.setBackgroundColor(MainActivity.context
					.getResources().getColor(R.color.GoogleGreen4));
			break;
		case 2:
			holder.buttonsBackground.setBackgroundColor(MainActivity.context
					.getResources().getColor(R.color.GoogleRed4));
			break;
		case 3:
			holder.buttonsBackground.setBackgroundColor(MainActivity.context
					.getResources().getColor(R.color.GoogleViolet4));
			break;
		case 4:
			holder.buttonsBackground.setBackgroundColor(MainActivity.context
					.getResources().getColor(R.color.GoogleOrange4));
			break;
		case 5:
			holder.buttonsBackground.setBackgroundColor(MainActivity.context
					.getResources().getColor(R.color.GoogleYellow4));
			break;
		case 6:
			holder.buttonsBackground.setBackgroundColor(MainActivity.context
					.getResources().getColor(R.color.GoogleBlue4));
			break;
		case 7:
			holder.buttonsBackground.setBackgroundColor(MainActivity.context
					.getResources().getColor(R.color.GoogleOrange4));
			break;
		case 8:
			holder.buttonsBackground.setBackgroundColor(MainActivity.context
					.getResources().getColor(R.color.GoogleViolet4));
			break;
		case 0:
			holder.buttonsBackground.setBackgroundColor(MainActivity.context
					.getResources().getColor(R.color.GoogleViolet4));
			break;
		}
		// }

		if (!componentsList.getPhoto().equals("")) {

//			if (!componentsList.getPhoto().equals("wifi01.jpg")) {
				final String imageKey = String.valueOf(componentsList.getId());

				final Bitmap bitmap = getBitmapFromMemCache(imageKey);
				if (bitmap != null) {
					holder.photo.setImageBitmap(bitmap);
					// holder.photo.setTag(componentsList.getImage());
					holder.photo.setVisibility(View.VISIBLE);
				} else {
					new getImage() {
						@Override
						protected void onPostExecute(Bitmap result) {
							if (result != null) {

								holder.photo.setImageBitmap(result);
								holder.photo.setVisibility(View.VISIBLE);
							} else {
								holder.photo.setVisibility(View.GONE);
								holder.photo.setTag("empty");
								int size = ((View) holder.photo.getParent())
										.getHeight();
							}
						}
					}.execute(componentsList.getPhoto(), holder.id.getText()
							.toString());
				}
//			} else {
//				holder.photo.setBackgroundResource(R.drawable.wifi01);
//				// holder.photo.setTag(componentsList.getImage());
//				holder.photo.setVisibility(View.VISIBLE);
//			}

		} else {
			holder.photo.setVisibility(View.GONE);
			holder.photo.setTag("empty");

		}

		return row;
	}

	static class ComponentsHolder {
		TextView id;
		TextView lat;
		TextView lng;
		TextView name;
		TextView address;
		TextView descr;
		ImageView photo;
		Button navigate;
		Button moreInfo;
		LinearLayout buttonsBackground;
	}

	public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
		if (getBitmapFromMemCache(key) == null) {
			MainActivity.mMemoryCache.put(key, bitmap);
		}
	}

	public final Bitmap getBitmapFromMemCache(String key) {
		return MainActivity.mMemoryCache.get(key);
	}

	private class getImage extends AsyncTask<String, String, Bitmap> {
		Bitmap photo;

		protected void onPreExecute() {
			// Mostramos el di�logo antes de comenzar
		}

		protected Bitmap doInBackground(String... urls) {

			// http://localhost:1313/menuvirtualws/services/OperatorClass/saveDishToOrder?idDish=0&idOrder=0&idTable=0&idWaiter=0&time=1240&comments=hola
			// client = new RestClient(urls[0]);
			Bitmap b = null;
			try {
				// client.Execute(RequestMethod.GET);

				b = BitmapFactory.decodeStream((InputStream) new URL(urls[0])
						.getContent());

				addBitmapToMemoryCache(urls[1], b);
			} catch (Exception e) {
				e.printStackTrace();
			}

			// Bitmap response = client.getResponse();
			// publishProgress(response);
			return b;
		}

		protected void onProgressUpdate(String... valores) {
			// ((TextView)findViewById(R.id.texto)).setText(valores[0].toString());

		}

		protected void onPostExecute(Bitmap img) {
			if (img != null) {
				photo = img;
			}
		}
	}
}
